<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="输入客户名进行搜索" v-model="queryInfo.query" clearable @clear="getUserList">
            <template #append>
              <el-button icon="Search" @click="getUserList"></el-button>

            </template>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="showDialog()">添加客户</el-button>
          <el-button type="primary" @click="exportExcel()">导出客户</el-button>
          <el-upload style="display: inline-block;margin-left: 12px;"  :on-success="uploadSucess" :on-error="uploadError"
            action="http://127.0.0.1:9999/common/member/import" :show-file-list="false"	:headers="headers">
            <el-button type="primary">导入客户</el-button>

          </el-upload>
            <el-button v-show="selectData.length > 0" @click="batchDelete" type="primary">批量删除</el-button>
        </el-col>
      </el-row>
      <!-- stripe隔行变色 -->
      <el-table :data="userList" :border="true" stripe style="width:100%" @select="selectChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="30px"></el-table-column>
        <el-table-column label="客户名" prop="memberName" width="180px"></el-table-column>
        <el-table-column label="邮箱" prop="memberEmail" width="180px"></el-table-column>
        <el-table-column label="电话" prop="memberPhone" width="180px"></el-table-column>
        <el-table-column label="生日" prop="memberBirthday" width="150px"></el-table-column>>
        <el-table-column label="操作" min-width="180px">
          <template #default="scope">
            <el-button type="primary" size="small" icon="Edit" @click="showDialog(scope.row.memberId)">编辑</el-button>

            <el-popconfirm width="220" icon="Delete" icon-color="#626AEF" title="永久删除，是否继续？" @cancel="cancelDelete"
              @confirm="confirmDelete(scope.row.memberId)">
              <template #reference>
                <el-button type="danger" icon="Delete" size="small">Delete</el-button>

              </template>
              <template #actions="{ confirm, cancel }">
                <el-button @click="cancel">取消</el-button>
                <el-button type="danger" @click="confirm">
                  确定
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        v-model:current-page="queryInfo.currentPage" v-model:page-size="queryInfo.pagesize" :page-sizes="[1, 2, 5, 10]"
        layout="prev, pager, next, jumper,total,sizes" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加/修改客户的对话框 -->
    <el-dialog :title=dialogTitle v-model="dialogVisible" width="30%">
      <!-- 主体 -->
      <el-form :model="dialogForm" ref="dialogRef" label-width="70px">
        <el-form-item label="客户名" prop="memberName">
          <el-input v-model="dialogForm.memberName"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="memberEmail">
          <el-input v-model="dialogForm.memberEmail"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="memberPhone">
          <el-input v-model="dialogForm.memberPhone"></el-input>
        </el-form-item>
        <el-form-item label="生日" prop="memberBirthday">
          <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" v-model="dialogForm.memberBirthday" type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <!--底部  -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="oprateUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script setup>
import axios from "axios";
import { ref, reactive, nextTick, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import qs from 'qs';
import FileSaver from "file-saver";

const { proxy } = getCurrentInstance()
let headers = {'token':localStorage.getItem('token')}
let clicked = ref(false)
let dialogTitle = ref()
let userList = ref([])
let queryInfo = reactive({
  query: "",
  //当前显示的页码
  pagenum: 1,
  pagesize: 5,
})
let dialogVisible = ref()

let dialogForm = ref({
  memberName: '',
  memberEmail: '',
  memberPhone: '',
  memberBirthday: ''
})

let total = ref(0)
let dialogRef = ref()
let selectData = ref([])

let getUserList = async function () {

  const { data: res } = await proxy.$http.get("/member/getList", {
    params: queryInfo,
  });
  console.log('res', res);
  if (res.code == 200) {
    userList.value = res.data.value;
    total.value = res.data.total;
  }
}

getUserList()

let dateFormat = function (date) {
  var year = date.getFullYear();
  /* 在日期格式中，月份是从0开始的，因此要加0
   * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
   * */
  var month =
    date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1;
  var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  // 拼接
  return year + "-" + month + "-" + day;
}

let showDialog = async function (mid, e) {

  dialogForm.value = {
    memberName: '',
    memberEmail: '',
    memberPhone: '',
    memberBirthday: ''
  }
  dialogVisible.value = true;//先显示窗口，再赋值，避免reset之后变成上一次的值

  console.log('mid', mid, e)
  dialogTitle.value = "新增客户"
  if (mid) {
    dialogTitle.value = "编辑客户"
    const { data: res } = await proxy.$http.get(
      "/member/getMemberById",
      { params: { id: mid } }
    );

    dialogForm.value = res.data;

  }

}

let oprateUser = async function () {
  let url
  if (dialogForm.value.memberId) {
    url = "/member/editMember"

  }
  else {
    url = "/member/addMember"
  }
  const { data: res } = await axios.post(
    url,
    dialogForm.value
  );

  if (res.code) {
    dialogVisible.value = false;
    getUserList();
  }

}


//监听pageSize改变的事件
let handleSizeChange = function (newSize) {
  queryInfo.pagesize = newSize;
  getUserList();
}
//监听页码改变的事件
let handleCurrentChange = function (newPage) {
  let pageCount = Math.ceil(total.value / queryInfo.pagesize);
  if (newPage <= pageCount) {
    queryInfo.pagenum = newPage;
    getUserList();
  }
}


let cancelDelete = function () {
  clicked.value = true
  return ElMessage("已取消删除");
}
let confirmDelete = async function (id) {
  const { data: result } = await axios.delete(
    `/member/deleteMember/${id}`
  );
  if (result.code) {
    getUserList()
    return ElMessage({
      message: result.message,
      type: "success",
    });
  }
}
function selectChange(val) {
  selectData.value = val
}
async function batchDelete() {
  let param = selectData.value.map((e) => e.memberId)
  console.log('param', param)
  const { data: result } = await axios.delete(
    '/member/batchDelete', {
    params: { idList: param },
    paramsSerializer: (params) => {
      // 将数组序列化为重复的键值对格式
      return qs.stringify(params, { arrayFormat: 'repeat' });
    }
  }
  );
  if (result.code) {
    getUserList()
    return ElMessage({
      message: result.message,
      type: "success",
    });
  }

}
const exportExcel = async function () {
  const result = await axios.get(
    '/member/export', { responseType: 'blob' },
  );
  FileSaver.saveAs(result, "客户列表.xls")

}

function uploadSucess(){
  ElMessage({
      message: "导入成功",
      type: "success",
    });
}
function uploadError(){
  ElMessage({
      message: "导入失败",
      type: "error",
    });
}

</script>

<style lang="less" scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

</style>